const transporter = require('../app/email')
const { USER_EMAIL } = require('../config/emailKey')
const {
  EMAIL_SEND_FAILED
} = require('../config/error')
const cache = require('../app/cache')
class EmailController {
  async send(ctx, next) {
    const email = ctx.query.email
    console.log(`output->email`, email)
    // 记得检测该 email 是否已注册
    const code = Math.random().toString().slice(2, 6)
    cache.set(email, code)
    const mailOptions = {
      from: USER_EMAIL,
      cc: USER_EMAIL,
      to: email,
      subject: '验证码',
      text: '说明内容',
      html: `<h2>智慧校园社团</h2>验证码：<span>${code}</span>`
    }
    try {
      await transporter.sendMail(mailOptions)
      ctx.body = {
        code: 0,
        message: '邮箱验证码发送成功！',
      }
    } catch (error) {
      ctx.app.emit('error', EMAIL_SEND_FAILED, ctx)
    }
  }
}


module.exports = new EmailController()